package Tree;

/**
 * 110.平衡二叉树
 * 给定一个二叉树，判断它是否是 平衡二叉树
 */
public class isBalanced {
    /**
     * 一刷
     */
    public boolean isBalanced(TreeNode root) {
        return height(root) >= 0;
    }

    public int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        } else {
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }

    /**
     * 二刷
     */
    public boolean isBalanced2(TreeNode root) {
        return getHeight(root) != -1;
    }

    private int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);	//左
        if (leftHeight == -1) {
            return -1;
        }
        int rightHeight = getHeight(root.right);	//右
        if (rightHeight == -1) {
            return -1;
        }
        // 左右子树高度差大于1，return -1表示已经不是平衡树了
        if (Math.abs(leftHeight - rightHeight) > 1) {	//中
            return -1;
        }
        return Math.max(leftHeight, rightHeight) + 1;
    }
}
